import requests
import json
import os

from Common.handle_path import uploadfile_dir
from Common.my_logger import logger
from Common.handle_config import conf


# 请求头前期处理
def __handle_header(headers):
    """
    处理请求头
    """
    if headers is not None and isinstance(headers, str):
        return eval(headers)

    return headers


# URL前期处理
def __pre_url(url):
    """
    拼接接口URL地址
    """
    host = conf.get("server", "host")
    if url.startswith("/"):
        return host + url
    else:
        return host + "/" + url


# 请求体data前期处理
def __pre_data(data):
    if data is not None and isinstance(data, str):
        return json.loads(data)
    return data


# 请求数据前期处理
def send_requests(method, url, data=None, headers=None, files=None):
    logger.info("发送一次HTTP请求")

    # 得到请求头
    headers = __handle_header(headers)
    # 得到完整的URL
    url = __pre_url(url)
    # 得到处理过后的请求体
    data = __pre_data(data)

    logger.info("请求头为:{}".format(headers))
    logger.info("请求方法为:{}".format(method))
    logger.info("请求URL为:{}".format(url))
    logger.info("请求数据为:{}".format(data))
    # 根据请求类型，调用请求方法;   method请求方法
    method = method.upper()  # 大写处理
    if files is not None:  # 文件上传
        file = {'file': open(os.path.join(uploadfile_dir, files), 'rb')}
        resp = requests.post(url=url, data=data, headers=headers, files=file)
        logger.info('进行文件上传')
    elif method == "GET":
        resp = requests.get(url, data, headers=headers)
    else:
        resp = requests.post(url, json=data, headers=headers)
    logger.info("响应状态码为:{}".format(resp.status_code))
    logger.info("响应数据为:{}".format(resp.json()))
    return resp


if __name__ == '__main__':
    login_url = "/ExamAPI/Common/Project/PCListV2"
    login_data = {'pageSize': '20', 'curPage': '1', 'e_using': '1', 'edu_levelid': '0', 'grd_no': '', 'e_name': '',
                  'userNo': 'wy05', 'status': '1'}
    headers = "{'token': '5232216993574d7481b9315f0c4cd154', 'Content_Type': 'application/json'}"
    token = '5232216993574d7481b9315f0c4cd154'
    Content_Type = 'application/json'

    # token=headers['token'], Content_Type=headers['Content_Type']

    header = __handle_header(headers)
    print(header)
